package m2;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws Exception{
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");  // wht6.cn
        // f.setPort(5672); //默认端口可以省略
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        //定义队列
        c.queueDeclare("task_queue", true, false, false, null);

        //准备好回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到："+s);
                // 遍历字符串，找到 '.' 字符暂停一秒
                for (int i = 0; i < s.length(); i++) {
                    if ('.' == s.charAt(i)) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                //s.length().for
                //参数 1.绘制数据 2.是否同时确认之前收到的所有消息
                c.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("消息处理完成");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        //qos=1,每次收一条，处理完之前不再接收
        //每次抓取的数量
        c.basicQos(1);
        //消费消息
        //第二个参数aotuAck，true-自动ack，false-手动ack
        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);
    }
}
